package cn.lcvc.xnc.authority.config.security.user;

import cn.lcvc.xnc.authority.config.security.TokenUtil;
import cn.lcvc.xnc.authority.service.SysUserTokenService;
import cn.lcvc.xnc.application.common.model.result.ResponseData;
import cn.lcvc.xnc.application.common.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义注销。
 * 注意，如果执行注销操作，自定义的token过滤器在注销之后再执行，所以这里的token要进行验证
 * 即验证后才允许注销
 */
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private SysUserTokenService sysUserTokenService;

    //注销成功后的请求
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //读取前端传递过来的token
        String token = TokenUtil.getToken(request);
        //从缓存中移除token,不再进行验证
        sysUserTokenService.removeUserToken(token);
//        ResponseUtil.responseJson(response, ResultCode.SUCCESS.getCode(), "成功注销用户");
        ResponseUtil.responseJson(response, ResponseData.success("成功注销用户"));

        /*if(StringUtils.hasLength(token)){
            try {
                //验证token是否合法
                sysUserTokenService.verifyUserToken(token);
                //从缓存中移除token
                sysUserTokenService.removeUserToken(token);
                ResponseUtil.responseJson(response, ResultCode.SUCCESS.getCode(), "成功注销用户");
            } catch (Exception e) {
                ResponseUtil.responseJson(response, ResultCode.UNAUTHORIZED.getCode(), e.getMessage());
            }
        }*/
        /*else{
            ResponseUtil.responseJson(response, ResultCode.UNAUTHORIZED.getCode(), "token为空，无法注销用户");
        }
*/
    }
}
